package com.glela.controller;

import com.alibaba.fastjson.JSONObject;
import com.glela.api.im.util.IMConfig;
import com.glela.cache.model.RedisKey;
import com.glela.cache.redis.RedisKeys;
import com.glela.common.constant.CommonConstants;
import com.glela.live.messages.*;
import com.glela.live.model.LivePlan;
import com.glela.live.model.LiveUserRecord;
import com.glela.live.model.request.ChartRoomRequest;
import com.glela.live.models.*;
import com.glela.live.service.ChatRoomService;
import com.glela.live.service.LivePlanService;
import com.glela.live.util.RongCloud;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/chatRoom")
public class ChatRoomController extends LiveBaseController {

	private static Logger logger = LoggerFactory.getLogger(ChatRoomController.class);

	@Autowired
	private ChatRoomService chatRoomService;

	@Autowired
	private LivePlanService livePlanService;

	@Autowired
	private UserService userService;

	/**
	 * 创建聊天室
	 *
	 * @param jsonObject
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/createChatRoom", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> createChartRoom(@RequestBody JSONObject jsonObject) {
		return new ResponseEntity<>(chatRoomService.createChatRoom(jsonObject),
				HttpStatus.OK);

	}

	/**
	 * 查询聊天室信息
	 *
	 * @param jsonObject
	 * @return
	 */
	@RequestMapping(value = "/query", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> query(@RequestBody JSONObject jsonObject) {
		return new ResponseEntity<>(chatRoomService.queryChatRoom(jsonObject),
				HttpStatus.OK);

	}

	/**
	 * 加入聊天室
	 *
	 * @param jsonObject
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/joinChatRoom", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> joinChartRoom(@RequestBody JSONObject jsonObject) {
		return new ResponseEntity<>(chatRoomService.joinChatRoom(jsonObject), HttpStatus.OK);

	}

	/**
	 * 获取token
	 *
	 * @param jsonObject
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getToken", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getToken(@RequestBody JSONObject jsonObject) {
		return new ResponseEntity<>(chatRoomService.getToken(jsonObject), HttpStatus.OK);

	}

	/**
	 * 查询聊天室用户列表
	 *
	 * @param jsonObject
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryRoomUsers", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> queryRoomUsers(@RequestBody JSONObject jsonObject){
		return new ResponseEntity<>(new ResponseResultModel<>(chatRoomService.queryRoomUsers(jsonObject)),
				HttpStatus.OK);

	}

	private static ExecutorService executorService = Executors.newFixedThreadPool(100);

	public void cacheLiveCountNum(final String key) {
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				ChatroomUserQueryResult chatroomQueryUserResult = null;
				try {
					chatroomQueryUserResult = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).chatroom
							.queryUser(key, "10", "2");
					redisUtil.set(redisUtil.get(RedisKeys.LIVE_USER_COUNT + key), chatroomQueryUserResult.getTotal());
					redisUtil.set(redisUtil.get(RedisKeys.LIVE_USER_COUNT + key + ":exp"), "1", 5);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 销毁聊天室
	 *
	 * @param jsonObject
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/destroyChatRoom", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> destroyChartRoom(@RequestBody JSONObject jsonObject) {
		return new ResponseEntity<>(chatRoomService.destroyChartRoom(jsonObject),
				HttpStatus.OK);

	}

	/**
	 * 添加聊天室禁言用户
	 *
	 * @param jsonObject
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addGagUser", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> addGagUser(@RequestBody JSONObject jsonObject){
		return new ResponseEntity<>(chatRoomService.addGagUser(jsonObject), HttpStatus.OK);
	}

	/**
	 * 查询聊天室禁言列表
	 *
	 * @param jsonObject
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryGagUser", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> queryGagUser(@RequestBody JSONObject jsonObject) {
		return new ResponseEntity<>(chatRoomService.queryGagUser(jsonObject), HttpStatus.OK);
	}

	/**
	 * 解除聊天室禁言
	 *
	 * @param jsonObject
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/rollbackGagUser", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> rollbackGagUser(@RequestBody JSONObject jsonObject){
		return new ResponseEntity<>(chatRoomService.rollbackGagUser(jsonObject),
				HttpStatus.OK);

	}

	/**
	 * 聊天室消息停止分发
	 */
	@RequestMapping(value = "/stopDistribution", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> stopDistribution(@RequestBody JSONObject jsonObject) {
		return new ResponseEntity<>(chatRoomService.stopDistribution(jsonObject),
				HttpStatus.OK);

	}

	/**
	 * 恢复聊天室消息分发
	 *
	 * @param jsonObject
	 * @return
	 */
	@RequestMapping(value = "/resumeDistribution", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> resumeDistribution(@RequestBody JSONObject jsonObject) {
		return new ResponseEntity<>(chatRoomService.resumeDistribution(jsonObject),
				HttpStatus.OK);

	}

	/**
	 * 发送聊天室消息
	 *
	 * @param jsonObject
	 * @return
	 */
	@RequestMapping(value = "/publish", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> publish(@RequestBody JSONObject jsonObject) {
		return new ResponseEntity<>(chatRoomService.publish(jsonObject), HttpStatus.OK);

	}

	@RequestMapping(value = "/publishGift", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> publishGift(@RequestBody JSONObject jsonObject) {
		return new ResponseEntity<>(chatRoomService.publishGift(jsonObject), HttpStatus.OK);

	}

	/**
	 * 对所有聊天室广播消息
	 *
	 * @param jsonObject
	 * @return
	 */
	@RequestMapping(value = "/fanout", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> fanout(@RequestBody JSONObject jsonObject) {
		return new ResponseEntity<>(chatRoomService.fanout(jsonObject), HttpStatus.OK);
	}

	@RequestMapping(value = "/history", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> history(@RequestBody JSONObject jsonObject) {
		return new ResponseEntity<>(chatRoomService.history(jsonObject), HttpStatus.OK);
	}

	/**
	 * 服务端接收app端点赞消息进行累计
	 * 
	 * @param jsonObject
	 * @return
	 */
	@RequestMapping(value = "/sendZmsg", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> sendZmsg(@RequestBody JSONObject jsonObject) {
		try {
			LivePlan livePlan = livePlanService.getById(jsonObject.getIntValue("id"));
			if (livePlan==null||livePlan.getStatus()!=2){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C90008), HttpStatus.OK);
			}
			int number = 0;
			try {
				number = jsonObject.getIntValue("number");
				if (number<=0){
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
				}
				if (number>100){
					number=100;
				}
			} catch (Exception e) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			}
			int count = chatRoomService.accumulationLikeTotal(jsonObject.getIntValue("id"),
					new Long(number));
			return new ResponseEntity<>(
							count > 0 ? new ResponseBaseModel(ErrorEnum.C10000) : new ResponseBaseModel(ErrorEnum.C10000),
					HttpStatus.OK);
		} catch (Exception e) {
			logger.error("服务端接收app端点赞消息进行累计失败", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 直播结束通知直播间消息
	 * 
	 * @param jsonObject
	 * @return
	 */
	@RequestMapping(value = "/liveDoneNotify", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> liveDoneNotify(@RequestBody JSONObject jsonObject) {
		try {
			LiveDoneMessage liveDoneMessage = new LiveDoneMessage();
			chatRoomService.mngSendMessage(jsonObject.getIntValue("liveUserId"),liveDoneMessage);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("直播结束通知直播间消息失败", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 发送直播间总人数、点赞数
	 * 
	 * @param jsonObject
	 * @return
	 */
	@RequestMapping(value = "/sendChatRoomDate", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> sendChatRoomDate(@RequestBody JSONObject jsonObject) {
		try {
			if (ParameterUtils.validParams(jsonObject.getIntValue("id"))) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			String likeTotal = redisUtil.get(RedisKeys.LIVE_PLAN_TOTAL_LIKE_NUM+jsonObject.getIntValue("id"))==null?0+"":redisUtil.get(RedisKeys.LIVE_PLAN_TOTAL_LIKE_NUM+jsonObject.getIntValue("id"));
			LivePlan livePlan = livePlanService.getById(jsonObject.getIntValue("id"));
			if (livePlan==null){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C90001), HttpStatus.OK);
			}
			String joinUserNum = redisUtil.get(RedisKeys.LIVE_PLAN_USER_NUMBER+jsonObject.getIntValue("id"));
			int userNum = joinUserNum==null?0:Integer.valueOf(joinUserNum);
			if (userNum<0){
				userNum=0;
			}
			ChatRoomDateMessage chatRoomDateMessage = new ChatRoomDateMessage(livePlan.getAddUserNum()+userNum,likeTotal==null?0:Integer.valueOf(likeTotal));
			chatRoomService.mngSendMessage(jsonObject.getIntValue("id"),chatRoomDateMessage);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("发送直播间总人数、点赞数失败", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	@RequestMapping(value = "/addLiveUserRecord", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> addLiveUserRecord(@RequestBody ChartRoomRequest request,HttpServletRequest httprequest) {
		logger.error("===============addLiveUserRecord=======id:"+request.getId()+"===========userid:"+request.getChatRoomUserId()+"=========action:"+request.getAction()+"=======phoneType:"+httprequest.getHeader("phoneType"));
		try {
			if (ParameterUtils.validParams(request.getAction())
					&& ParameterUtils.validParams(request.getChatRoomUserId())
					&& ParameterUtils.validParams(request.getId())) {
				logger.error("===============addLiveUserRecorderror=======id:"+request.getId()+"===========userid:"+request.getChatRoomUserId()+"=========action:"+request.getAction()+"=======phoneType:"+httprequest.getHeader("phoneType"));
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			LivePlan livePlan = livePlanService.getById(request.getId());
			if (livePlan==null){
				logger.error("===============addLiveUserRecorderror-liveplan=======id:"+request.getId()+"===========userid:"+request.getChatRoomUserId()+"=========action:"+request.getAction()+"=======phoneType:"+httprequest.getHeader("phoneType"));
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C90001), HttpStatus.OK);
			}
			/*User cuser = userService.getUser(Long.valueOf(request.getChatRoomUserId()));
			if (cuser==null){
				logger.error("===============addLiveUserRecorderror-user=======id:"+request.getId()+"===========userid:"+request.getChatRoomUserId()+"=========action:"+request.getAction()+"=======phoneType:"+httprequest.getHeader("phoneType"));
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C90006), HttpStatus.OK);
			}*/
			System.out.println("====");
//			chatRoomService.addLiveUserRecord(request.getAction(), request.getChatRoomUserId(), request.getId());
			LiveUserRecord liveUserRecord = new LiveUserRecord();
			liveUserRecord.setAction(request.getAction());
			liveUserRecord.setLivePlanId(request.getId());
			liveUserRecord.setUserId(request.getChatRoomUserId());
			liveUserRecord.setCreatedDate(new Date());
			liveUserRecord.setOpenId(StringUtils.isNotBlank(request.getOpenId())?request.getOpenId():"");
			int clientType = 3;
			if (StringUtils.isNotBlank(httprequest.getHeader("phoneType")) && httprequest.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_IOS)){
				clientType = 1;
			}
			if (StringUtils.isNotBlank(httprequest.getHeader("phoneType")) && httprequest.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_ANDROID)){
				clientType = 2;
			}
			liveUserRecord.setClient(clientType);
			//有openid说明是h5请求
			if (StringUtils.isBlank(liveUserRecord.getOpenId())) {
				if (0 == request.getAction()) {    //0:进入直播间
					redisUtil.incr(RedisKeys.LIVE_PLAN_USER_NUMBER + request.getId());
				}
				if (1 == request.getAction()) {    //1：离开直播间
					String nums = redisUtil.get(RedisKeys.LIVE_PLAN_USER_NUMBER + request.getId());
					if (nums != null && Integer.valueOf(nums) >= 1) {
						redisUtil.decr(RedisKeys.LIVE_PLAN_USER_NUMBER + request.getId());
					}
				}
			}else{
				redisUtil.zadd(RedisKey.REDIS_KEY_LIVE_H5_RECORD_SET+request.getId(),System.currentTimeMillis(),liveUserRecord.getOpenId());
			}
			redisUtil.rpush(RedisKey.REDIS_KEY_LIVE_PLAN_USER_RECORD+request.getId(),JSONObject.toJSONString(liveUserRecord));
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("记录用户出入聊天室信息失败", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	@RequestMapping(value = "/liveUserHeartbeat", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> liveUserHeartbeat(@RequestBody ChartRoomRequest request){
		try {
			redisUtil.zadd(RedisKey.REDIS_KEY_LIVE_H5_RECORD_SET+request.getId(),System.currentTimeMillis(),request.getOpenId());
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		}catch (Exception e){
			logger.error("liveUserHeartbeat====error====userId:"+request.getUserId()+"====openId:"+request.getOpenId());
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	@RequestMapping("/testSendZan")
	public String testZan(){
		com.glela.live.messages.User user = new com.glela.live.messages.User("366","","");
		final ZanMessage zanMessage  = new ZanMessage(100,user);
		sendZ(zanMessage);
		return "ok";
	}


	//private static ExecutorService executorService	= Executors.newFixedThreadPool(20);

	public void sendZ(final ZanMessage zanMessage) {
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < 1000; i++) {
					System.out.println("===============");
					chatRoomService.mngSendMessage(16,zanMessage);
				}
			}
		});
	}

	@RequestMapping(value = "/getssrs", method = RequestMethod.POST, consumes = "application/json")
	public String getssrs(@RequestBody JSONObject json){
		while (StringUtils.isNotBlank(redisUtil.get(RedisKeys.LIVE_ROOM_EXECUT_LIVE_PLAN+json.getIntValue("id")))) {
			chatRoomService.addLiveAudience(json.getIntValue("id"));
			try {
				Thread.sleep(CommonConstants.sendChatRoomInfoRate);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return "ok";
	}

	/**
	 * 向直播间发红包接口
	 * @param json
	 * @return
	 */
	@RequestMapping(value = "/sendRedPackage",method = RequestMethod.POST,consumes = "application/json")
	public ResponseEntity<?> sendRedPackage(@RequestBody JSONObject json){
		try {
			RedPackageMessage redPackageMessage = new RedPackageMessage(json.getInteger("redPackageId"));
			chatRoomService.mngSendMessage(json.getIntValue("id"),redPackageMessage);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("向直播间发送红包消息失败", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

}
